package com.sysmanage.permissions.controls;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.sysmanage.common.tools.util.DictionaryMemoryUtils;
import com.sysmanage.framework.controls.struts2.BaseTg;
import com.sysmanage.permissions.ConstCode;
import com.sysmanage.permissions.model.Company;
import com.sysmanage.permissions.service.ICompanyService;
import com.sysmanage.permissions.tree.Utils;
import com.sysmanage.tree.Node;
import com.sysmanage.tree.UncodeException;
import com.sysmanage.tree.UserDataUncoder;
import com.sysmanage.tree.support.AbstractWebTreeModelCreator;
import com.sysmanage.tree.support.WebTreeNode;


/** 
  * @ClassName: CountyTg 
  * @Description: 公司信息控制层
  * @author XXXX@163.com
  * @date 2011-9-26 上午9:12:04 
  *  
  */
@SuppressWarnings("serial")
@Scope("prototype")
@Controller("permissions.companyControl")
public class CompanyTg extends BaseTg {
	/** 
	  * @Fields companyService : ICompanyService接口spring注入 
	  */ 
	@Autowired
	private ICompanyService companyService;
	
	/** 
	  * @Fields company : struts2.0自动接受
	  */ 
	private Company company;
	
	/** 
	  * @Fields id : 要删除的id
	  */ 
	private String id;

	
	
	public void getTree(){
		
		List<Map<String,Object>> list = this.companyService.getTree(this.getCurrentUserCompanyID());
		outJsonPlainString(response, JSONArray.fromObject(list).toString());
	}
	
	
	/** 
	  * @Title: all 
	  * @Description: 获得所有的公司
	  * @param 
	  * @return void
	  * @throws 
	  */
	public void all(){
		List<Company> list = companyService.getAll();
		JSONArray jsonArray = JSONArray.fromObject(doOther(list));
		returnJsion(jsonArray.toString(),response);
	}
	
	/** 
	  * @Title: update 
	  * @Description: 更新公司的信息
	  * @param 
	  * @return void
	  * @throws 
	  */
	public void update(){
		if(company.getParentId()!=null&&(company.getParentId()==-1||company.getParentId()==company.getId()))
		{
			company.setParentId(null);
		}		
		if(this.companyService.alter(company)){
			reloadMemory();
			returnJsion("{\"success\":\"true\"}",response);
		}else{
			returnJsion("{\"error\":\"true\"}",response);
		}
	}
	
	/** 
	  * @Title: find 
	  * @Description: 根据id查找公司的信息
	  * @param 
	  * @return void
	  * @throws 
	  */
	public void find(){
		Company company = this.companyService.findById(Integer.valueOf(id));
		List<Company> list = new ArrayList<Company>();
		if(null != company){
			list.add(company);
		}
		JSONArray jsonArray = JSONArray.fromObject(doOther(list));
		
		if(null != company.getParentId()){
			Company temp = this.companyService.findById(company.getParentId());
			returnJsion("{\"rows\":" + jsonArray.toString() + ",\"parentid\":\"" + temp.getId() + "\",\"parentName\":\"" + temp.getCompanyName() + "\"}",response);
		}else{
			returnJsion("{\"rows\":" + jsonArray.toString() + ",\"parentid\":\"\"}",response);
		}
	}
	
	/** 
	  * @Title: del 
	  * @Description: 根据id删除公司的信息
	  * @param 
	  * @return void
	  * @throws 
	  */
	public void del(){
		/*
		if(this.companyService.deleteById(Long.valueOf(id))){
			returnJsion("{\"success\":\"true\"}",response);
		}else{
			returnJsion("{\"error\":\"true\"}",response);
		}
		*/
		company = this.companyService.findById(Integer.valueOf(id));
		company.setStatus(ConstCode.STATUS_DELETE);
		update();
	}
	
	/** 
	  * @Title: save 
	  * @Description: 保存一条公司的记录
	  * @param 
	  * @return void
	  * @throws 
	  */
	public void save(){
		if(company.getParentId()!=null&&company.getParentId()==-1)
		{
			company.setParentId(null);
		}
		if(this.companyService.save(company)){
			reloadMemory();
			returnJsion("{\"success\":\"true\"}",response);
		}else{
			returnJsion("{\"error\":\"true\"}",response);
		}
	}
	
	/** 
	  * @Title: list 
	  * @Description: 获取所有公司，并且用tree来显示
	  * @param @return
	  * @return String 一段<html>代码
	  * @throws 
	  */
	public void list(){
		List<Company> list = companyService.getAll();
		// 业务数据解码器，从业务数据中分解出id和parentid
		UserDataUncoder orgUncoder = new UserDataUncoder() {
			public Object getID(Object pUserData) throws UncodeException {
				Company org = (Company) pUserData;
				return org.getId();
			}

			public Object getParentID(Object pUserData) throws UncodeException {
				Company org = (Company) pUserData;
				return org.getParentId();
			}
		};

		// Tree模型构造器，用于生成树模型
		AbstractWebTreeModelCreator treeModelCreator = new AbstractWebTreeModelCreator() {
			// 该方法负责将业务数据映射到树型节点
			protected Node createNode(Object pUserData, UserDataUncoder pUncoder) {
				Company org = (Company) pUserData;
				WebTreeNode result = new WebTreeNode(org.getCompanyName(), "node"+org.getId(),org);

				return result;
			}
		};
		String temp = Utils.showeasyuiTree(orgUncoder, treeModelCreator, list, request);
		outHtmlUTFString(response,temp);
	}

	/** 
	  * @Title: index 
	  * @Description: 组的首页信息
	  * @param @return
	  * @return String
	  * @throws 
	  */
	public String index(){
		List<Company> list = companyService.getAll();
		// 业务数据解码器，从业务数据中分解出id和parentid
		UserDataUncoder orgUncoder = new UserDataUncoder() {
			public Object getID(Object pUserData) throws UncodeException {
				Company org = (Company) pUserData;
				return org.getId();
			}

			public Object getParentID(Object pUserData) throws UncodeException {
				Company org = (Company) pUserData;
				return org.getParentId();
			}
		};

		// Tree模型构造器，用于生成树模型
		AbstractWebTreeModelCreator treeModelCreator = new AbstractWebTreeModelCreator() {
			// 该方法负责将业务数据映射到树型节点
			protected Node createNode(Object pUserData, UserDataUncoder pUncoder) {
				Company org = (Company) pUserData;
				WebTreeNode result = new WebTreeNode(org.getCompanyName(), "node"+org.getId(),org);
				return result;
			}
		};
		String temp = Utils.showeasyuiTree(orgUncoder, treeModelCreator, list, request);
		request.setAttribute("treeScript", temp);
		return this.SUCCESS;
	}

	/** 
	  * @Title: returnJsion 
	  * @Description: 解决json问题
	  * @param @param baseStr
	  * @param @param response
	  * @return void
	  * @throws 
	  */
	private void returnJsion(String baseStr, HttpServletResponse response) {
		response.setContentType("text/plain;charset=UTF-8");
		PrintWriter out = null;
		try {
			out = response.getWriter();
			out.print(baseStr);
			out.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			if (out != null) {
				out.close();
			}
		}
		
	}
	
	/** 
	  * @Title: doOther 
	  * @Description: 解决struts2.0domal接受参数的方法
	  * @param @param list 装Company的具体信息。
	  * @param @return
	  * @return List
	  * @throws 
	  */
	private List doOther(List<Company> list) {
		List lists = new ArrayList();
		if(list != null && list.size() > 0){
			for(int i =0;i<list.size();i++){
				Map<String,String> map = new HashMap<String, String>();
				Company item = list.get(i);
				map.put("id", item.getId() + "");
				
				if(null!=item.getCompanyName()){
			        map.put("companyName", item.getCompanyName());
				}
				else
					map.put("companyName", "");
				
				if(null!=item.getParentId()){
			        map.put("parentId", item.getParentId()+"");
				}
				else
					map.put("parentId", "");
				if(null!=item.getCompany()){
			        map.put("parentCompanyName", item.getCompany().getCompanyName()+"");
				}
				else
					map.put("parentId", "");				
				if(null!=item.getPhone()){
			        map.put("phone", item.getPhone());
				}
				else
					map.put("phone", "");
				
				if(null!=item.getManager()){
			        map.put("manager", item.getManager());
				}
				else
					map.put("manager", "");
				
				if(null!=item.getManagerPhone()){
			        map.put("managerPhone", item.getManagerPhone());
				}
				else
					map.put("managerPhone", "");
				
				if(null!=item.getContactPerson()){
			        map.put("contactPerson", item.getContactPerson());
				}
				else
					map.put("contactPerson", "");
				
				if(null!=item.getContactPhone()){
			        map.put("contactPhone", item.getContactPhone());
				}
				else
					map.put("contactPhone", "");
				
				if(null!=item.getAreaId()){
			        map.put("areaId", item.getAreaId()+"");
				}
				else
					map.put("areaId", "");
				
				if(null!=item.getAddress()){
			        map.put("address", item.getAddress());
				}
				else
					map.put("address", "");
				
				if(null!=item.getLatitude()){
			        map.put("latitude", item.getLatitude()+"");
				}
				else
					map.put("latitude", "");
				
				if(null!=item.getLongitude()){
			        map.put("longitude", item.getLongitude()+"");
				}
				else
					map.put("longitude", "");
				
				if(null!=item.getCompanyType()){
			        map.put("companyType", item.getCompanyType()+"");
				}
				else
					map.put("companyType", "");
				
				if(null!=item.getCompanyDescription()){
			        map.put("companyDescription", item.getCompanyDescription());
				}
				else
					map.put("companyDescription", "");
				
				if(null!=item.getCompanyImagePaht()){
			        map.put("companyImagePaht", item.getCompanyImagePaht());
				}
				else
					map.put("companyImagePaht", "");
				
				map.put("weiXinNumber",item.getWeiXinNumber());
				map.put("token",item.getToken());
				map.put("appID",item.getAppID());
				map.put("appsecret",item.getAppsecret());
				map.put("accessToken",item.getAccessToken());
				map.put("atValidTime",item.getAtValidTime().toString());
				
				map.put("ext1",item.getExt1());
				map.put("ext2",item.getExt2());
				map.put("ext3",item.getExt3());
				map.put("ext4",item.getExt4());
				map.put("status",item.getStatus()+"");
				lists.add(map);
			}
		}else{
			Map<String,String> map = new HashMap<String, String>();
			map.put("error", "error");
			lists.add(map);
		}
		return lists;
	}

	private void reloadMemory(){
		DictionaryMemoryUtils dictionaryUtils = DictionaryMemoryUtils.getInstance();
		dictionaryUtils.refreshDic(ConstCode.DIC_NICK_NAME_COMPANY, company.getCompanyName(), company.getId()+"");
	}
	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}


	public ICompanyService getCompanyService() {
		return companyService;
	}


	public void setCompanyService(ICompanyService companyService) {
		this.companyService = companyService;
	}


	public Company getCompany() {
		return company;
	}


	public void setCompany(Company company) {
		this.company = company;
	}
}
